from flask_restful import Resource, reqparse
import os
from flask import jsonify

# 获取当前文件的目录
BASE_DIR = os.path.dirname(os.path.abspath(__file__))

# 定义保存文件的目录
SAVE_FOLDER = os.path.join(BASE_DIR, '../data/finetune_sets')

# 确保目录存在
if not os.path.exists(SAVE_FOLDER):
    os.makedirs(SAVE_FOLDER)

class SAVEFILE(Resource):
    def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument('file_name', required=True, help='File name cannot be blank')
        self.parser.add_argument('conversations', required=True, help='Conversations cannot be blank')

    def post(self):
        args = self.parser.parse_args()
        file_name = args['file_name']
        conversations = args['conversations']

        # 文件路径
        file_path = os.path.join(SAVE_FOLDER, file_name)

        # 创建文件（如果不存在）并写入数据
        with open(file_path, 'a', encoding='utf-8') as f:
            f.write(conversations)  # 每次写入后换行

        return jsonify({"message": "Data saved successfully", "file_name": file_name})
